package com.test.test01.schedule.runner;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.test.test01.bean.SystemJob;
import com.test.test01.schedule.register.CronTaskRegister;
import com.test.test01.schedule.runnable.SchedulingRunnable;
import com.test.test01.service.SystemJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * Description: 系统定时任务运行  项目启动前加载:从数据库中取出定时任务开始之执行
 * Create DateTime: 2021/1/5 上午10:17
 *
 * @author houyi
 */
@Slf4j
@Component
public class SystemJobRunner implements CommandLineRunner {

    @Resource
    private CronTaskRegister cronTaskRegister;

    @Resource
    private SystemJobService systemJobService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    public void run(String... args) {
        List<SystemJob> systemJobList = systemJobService.list(Wrappers.lambdaQuery(SystemJob.class)
                .eq(SystemJob::getJobStatus, 1).eq(SystemJob::getDeleteFlag, 0));
        if (CollectionUtil.isEmpty(systemJobList)) {
            return;
        }
        for (SystemJob job : systemJobList) {
            SchedulingRunnable task = new SchedulingRunnable(job.getId(), job.getBeanName(), job.getMethodName(), job.getMethodParams(),
                    job.getJobCount(), job.getCronExpression(), cronTaskRegister, jdbcTemplate, transactionTemplate);
            cronTaskRegister.addCronTask(task, job.getCronExpression());
        }
        log.info("系统定时任务加载完毕");
    }
}
